var createError = require('http-errors');
var express = require('express');
var fs = require("fs");
var path = require('path');
var https = require("https");
var cookieParser = require('cookie-parser');
var base64 = require("js-base64").Base64;
var ping = require("ping");
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();
app.listen(8077);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.all('*',function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

    if (req.method == 'OPTIONS') {
        res.send(200); /让options请求快速返回/
    }
    else {
        next();
    }
});
app.use('/', indexRouter);
app.use('/users', usersRouter);


app.get("/getfree",function (req,res) {

    let mycode = base64.encode("mcydptr");
    let remark = base64.encode("板栗");
    let ssrs = "";
    https.get("https://heikejilaila.xyz/keji.php?id=3daec4bff9f34b592b3d9abd3d5dbff9",function (data) {

        ssrs="";
        data.on("data",function (chunk) {

            ssrs+=chunk;
        });
        data.on("end",function () {



            let result = base64.decode(ssrs);
            let ssrlist = result.split('\n');
            let ssrarry = [];
            let hosts=[];
            for(let i = 0;i<ssrlist.length-1;i++){

                let item = ssrlist[i].slice(6,ssrlist[i].length);
                let rs = base64.decode(item);
                let min = rs.split("group");

                let end = "";
                let host = ""
                if(min[1].length>=21){

                    let a = min[0].split("remarks");
                    a = a+"remarks="+remark+"&";
                    end = a+'group='+mycode+ (min[1].slice(21,min[1].length));
                    host = end.split(":")[0];
                    end='ssr://'+base64.encode(end);
                }
                ssrarry.push(end);
                hosts.push(host);
            }
            res.json({sss:ssrarry,hosts:hosts});

        });


    });


});


app.get("/chestnutordinarypersonwithouttalent",function (req,res) {

    let mycode = base64.encode("mcydptr");
    let rd="";
    let remark = base64.encode("板栗");
    let ssrs = "";
    https.get("https://heikejilaila.xyz/keji.php?id=3daec4bff9f34b592b3d9abd3d5dbff9",function (data) {

        data.on("data",function (chunk) {

            ssrs+=chunk;
        });
        data.on("end",function () {


            let result = base64.decode(ssrs);
            let ssrlist = result.split('\n');
            let hosts=[];
            for(let i = 0;i<ssrlist.length-1;i++){

                let item = ssrlist[i].slice(6,ssrlist[i].length);
                let rs = base64.decode(item);
                let min = rs.split("group");
                let end = "";
                let host = ""
                if(min[1].length>=21){

                    let a = min[0].split("remarks")[0];
                    a = a+"remarks="+remark+"&";
                    end = a +'group='+mycode+ (min[1].slice(21,min[1].length));
                    end='ssr://'+base64.encode(end)+'\n';
                    rd+=end;

                }else{

                    console.log("OOOP");
                }

            }

            let resultlist=base64.encode(rd);
            res.send(resultlist);

        });


    });


});

app.get("/check",function (req,res) {

    let hosts =  req.query.hosts.split(",");
    console.log(hosts);
    let alives = [];
    let index=0;
    function checknext() {

        if(index>=hosts.length){

            res.json(alives);
            return;
        }
        ping.sys.probe(hosts[index], function(isAlive){
            var msg = isAlive ? 1 : 0;
            alives.push(msg);
            index++;
            checknext();

        });
    }

    checknext();

});

// http://qr.topscan.com/api.php?text=



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

